package com.acane.instagram.feature.search

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.acane.instagram.R
import com.acane.instagram.core.config.Config
import com.acane.instagram.core.design.theme.InstagramLightGray
import com.acane.instagram.core.model.PostInfo
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState

@Composable
fun SearchRoute(
    toSearchDetail: () -> Unit,
) {
    SearchScreen(
        toSearchDetail = toSearchDetail,
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun SearchScreen(
    searchViewModel: SearchViewModel = viewModel(),
    toSearchDetail: () -> Unit
) {
    val imageList = List(15) {
        painterResource(id = R.drawable.avatar)
    } // 使用合适的图片资源

    val refreshState by searchViewModel.refresh.collectAsState()

    val swipeRefresh = rememberSwipeRefreshState(isRefreshing = refreshState)

    SwipeRefresh(state = swipeRefresh, onRefresh = {
        searchViewModel.startRefresh()
    }) {
        Scaffold(
            topBar = {
                TopAppBar(
                    title = {
                    },
                    actions = {
                        // 搜索框按钮
                        Row (

                        ) {
                            Button(
                                onClick = {
                                    // 跳转到搜索详情页面
                                    toSearchDetail()
                                },
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = InstagramLightGray,
                                    contentColor = Color.Black
                                ),
                                modifier = Modifier
                                    .height(30.dp)
                                    .padding(horizontal = 4.dp)
                                    .width(450.dp),
                                shape = RoundedCornerShape(5.dp),
                                elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp) // 设置内容内边距
                            ) {
                                Image(
                                    painter = painterResource(id = R.drawable.search),
                                    contentDescription = null,
                                    modifier = Modifier
                                        .padding(end = 4.dp)
                                        .size(20.dp),
                                    contentScale = ContentScale.Crop
                                )
                                Text(
                                    text = "搜索",
                                    fontSize = 12.sp,
                                )
                            }
                        }
                    },
                    colors = TopAppBarDefaults.centerAlignedTopAppBarColors().copy(
                        containerColor = Color.Transparent
                    )
                )
            },
            contentColor = Color.White,
            containerColor = Color.White
        ) { paddingValues ->
            Box (
                modifier = Modifier.padding(paddingValues)
            ) {
                SearchCustomImageLayout(imageList)
            }
        }
    }

}
@Composable
fun CustomImageLayout(
    postSearchResultData: List<PostInfo>,
    searchViewModel: SearchViewModel,
    toPost: (String, Int) -> Unit,
    toDetail: (String) -> Unit,
) {
    LazyColumn(modifier = Modifier.fillMaxSize()) {

        itemsIndexed(postSearchResultData.chunked(5)) { index, rowImages ->
            // 动态计算实际元素数量
            val actualSize = rowImages.size

            // 空行不渲染
            if (actualSize == 0) return@itemsIndexed

            // 判断当前行的索引来确定长方形的位置
            val isRectangleOnLeft = index % 2 == 0 // 判断偶数行或奇数行

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(IntrinsicSize.Min)
            ) {

            }
            if (isRectangleOnLeft) {
                // 第一种布局：长方形在左，正方形在右
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(IntrinsicSize.Min)
                ) {
                    Box(
                        modifier = Modifier
                            .weight(0.5f)
                            .aspectRatio(1f / 2f) // 长方形宽高比
                    ) {
                        //postPosition = searchViewModel.getPostPosition(rowImages[0].id)
                        if (rowImages.isNotEmpty()) {
                            AsyncImage(
                                model = rowImages[0].thumbnailUrl.let {
                                    val url = "${Config.ADDRESS}avatars/$it"
                                    Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                                    url
                                },
                                contentScale = ContentScale.Crop,
                                contentDescription = "当前用户头像",
                                modifier = Modifier
                                    .fillMaxSize()
                                    .clickable {
                                        toDetail(rowImages[0].id)
                                    },
                                error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                            )
                        }
                    }

                    // 正方形区域
                    Column(
                        modifier = Modifier
                            .weight(1f)
                            .height(IntrinsicSize.Min) // 关键修改点
                    ) {
                        // 第一行正方形
                        Row(modifier = Modifier.weight(1f)) {
                            rowImages.drop(1).take(2).forEach { image ->
                                //postPosition = searchViewModel.getPostPosition(image.id)
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .aspectRatio(1f)
                                ) {
                                    AsyncImage(
                                        model = image.thumbnailUrl.let {
                                            val url = "${Config.ADDRESS}avatars/$it"
                                            Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                                            url
                                        },
                                        contentScale = ContentScale.Crop,
                                        contentDescription = "当前用户头像",
                                        modifier = Modifier
                                            .fillMaxSize()
                                            .clickable {
                                                //userId?.let { toPost(it, postPosition) }
                                            },
                                        error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                                    )
                                }
                            }
                        }

                        // 第二行正方形
                        Row(modifier = Modifier.weight(1f)) {
                            rowImages.drop(3).take(2).forEach { image ->
                                //postPosition = searchViewModel.getPostPosition(image.id)
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .aspectRatio(1f)
                                ) {
                                    AsyncImage(
                                        model = image.thumbnailUrl.let {
                                            val url = "${Config.ADDRESS}avatars/$it"
                                            Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                                            url
                                        },
                                        contentScale = ContentScale.Crop,
                                        contentDescription = "当前用户头像",
                                        modifier = Modifier
                                            .fillMaxSize()
                                            .clickable {
                                                //userId?.let { toPost(it, postPosition) }
                                            },
                                        error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                                    )
                                }
                            }
                        }
                    }
                }
            } else {
                // 第二种布局：长方形在右，正方形在左
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(IntrinsicSize.Min)
                ) {
                    // 正方形区域
                    Column(
                        modifier = Modifier
                            .weight(1f)
                            .height(IntrinsicSize.Min) // 关键修改点
                    ) {
                        // 第一行正方形
                        Row(modifier = Modifier.weight(1f)) {
                            rowImages.drop(1).take(2).forEach { image ->
                                //postPosition = searchViewModel.getPostPosition(image.id)
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .aspectRatio(1f)
                                ) {
                                    AsyncImage(
                                        model = image.thumbnailUrl.let {
                                            val url = "${Config.ADDRESS}avatars/$it"
                                            Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                                            url
                                        },
                                        contentScale = ContentScale.Crop,
                                        contentDescription = "当前用户头像",
                                        modifier = Modifier
                                            .fillMaxSize()
                                            .clickable {
                                                //userId?.let { toPost(it, postPosition) }
                                            },
                                        error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                                    )
                                }
                            }
                        }

                        // 第二行正方形
                        Row(modifier = Modifier.weight(1f)) {
                            rowImages.drop(3).take(2).forEach { image ->
                                //postPosition = searchViewModel.getPostPosition(image.id)
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .aspectRatio(1f)
                                ) {
                                    AsyncImage(
                                        model = image.thumbnailUrl.let {
                                            val url = "${Config.ADDRESS}avatars/$it"
                                            Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                                            url
                                        },
                                        contentScale = ContentScale.Crop,
                                        contentDescription = "当前用户头像",
                                        modifier = Modifier
                                            .fillMaxSize()
                                            .clickable {
                                               // userId?.let { toPost(it, postPosition) }
                                            },
                                        error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                                    )
                                }
                            }
                        }
                    }

                    Box(
                        modifier = Modifier
                            .weight(0.5f)
                            .aspectRatio(1f / 2f) // 长方形宽高比
                    ) {
                      //  postPosition = searchViewModel.getPostPosition(rowImages[0].id)
                        if (rowImages.isNotEmpty()) {
                            AsyncImage(
                                model = rowImages[0].thumbnailUrl.let {
                                    val url = "${Config.ADDRESS}avatars/$it"
                                    Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                                    url
                                },
                                contentScale = ContentScale.Crop,
                                contentDescription = "当前用户头像",
                                modifier = Modifier
                                    .fillMaxSize()
                                    .clickable {
                                      //  userId?.let { toPost(it, postPosition) }
                                    },
                                error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun SearchCustomImageLayout(imageList: List<Painter>) {
    LazyColumn(modifier = Modifier.fillMaxSize()) {
        itemsIndexed(imageList.chunked(5)) { index, rowImages ->
            // 判断当前行的索引来确定长方形的位置
            val isRectangleOnLeft = index % 2 == 0 // 判断偶数行或奇数行

            if (isRectangleOnLeft) {
                // 第一种布局：长方形在左，正方形在右
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(IntrinsicSize.Min)
                ) {
                    Box(
                        modifier = Modifier
                            .weight(0.5f)
                            .aspectRatio(1f / 2f) // 长方形宽高比
                    ) {
                        if (rowImages.isNotEmpty()) {
                            Image(
                                painter = rowImages[0],
                                contentDescription = null,
                                modifier = Modifier.fillMaxSize(),
                                contentScale = ContentScale.Crop
                            )
                        }
                    }

                    // 正方形区域
                    Column(
                        modifier = Modifier
                            .weight(1f)
                            .height(IntrinsicSize.Min) // 关键修改点
                    ) {
                        // 第一行正方形
                        Row(modifier = Modifier.weight(1f)) {
                            rowImages.drop(1).take(2).forEach { image ->
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .aspectRatio(1f)
                                ) {
                                    Image(
                                        painter = image,
                                        contentDescription = null,
                                        modifier = Modifier.fillMaxSize()
                                    )
                                }
                            }
                        }

                        // 第二行正方形
                        Row(modifier = Modifier.weight(1f)) {
                            rowImages.drop(3).take(2).forEach { image ->
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .aspectRatio(1f)
                                ) {
                                    Image(
                                        painter = image,
                                        contentDescription = null,
                                        modifier = Modifier.fillMaxSize()
                                    )
                                }
                            }
                        }
                    }
                }
            } else {
                // 第二种布局：长方形在右，正方形在左
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(IntrinsicSize.Min)
                ) {
                    // 正方形区域
                    Column(
                        modifier = Modifier
                            .weight(1f)
                            .height(IntrinsicSize.Min) // 关键修改点
                    ) {
                        // 第一行正方形
                        Row(modifier = Modifier.weight(1f)) {
                            rowImages.drop(1).take(2).forEach { image ->
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .aspectRatio(1f)
                                ) {
                                    Image(
                                        painter = image,
                                        contentDescription = null,
                                        modifier = Modifier.fillMaxSize()
                                    )
                                }
                            }
                        }

                        // 第二行正方形
                        Row(modifier = Modifier.weight(1f)) {
                            rowImages.drop(3).take(2).forEach { image ->
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .aspectRatio(1f)
                                ) {
                                    Image(
                                        painter = image,
                                        contentDescription = null,
                                        modifier = Modifier.fillMaxSize()
                                    )
                                }
                            }
                        }
                    }

                    Box(
                        modifier = Modifier
                            .weight(0.5f)
                            .aspectRatio(1f / 2f) // 长方形宽高比
                    ) {
                        if (rowImages.isNotEmpty()) {
                            Image(
                                painter = rowImages[0],
                                contentDescription = null,
                                modifier = Modifier.fillMaxSize(),
                                contentScale = ContentScale.Crop
                            )
                        }
                    }
                }
            }
        }
    }
}




@Preview(showBackground = true)
@Composable
fun PreviewCustomImageLayout() {
    //SearchScreen()
}
